package com.bobo.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bobo.domain.SysMenu;
import com.bobo.service.SysMenuService;
import com.bobo.mapper.SysMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author THINKAPD
* @description 针对表【sys_menu】的数据库操作Service实现
* @createDate 2022-11-18 10:50:54
*/
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
    implements SysMenuService{
    @Autowired
    SysMenuMapper sysMenuMapper;

    @Override
    public List<Tree<String>> getTreeMenu(String username) {

        List<SysMenu> nodeList=null;
        if("admin".equals(username)){
            //1 获取所有菜单
          nodeList = sysMenuMapper.selectList(null);
        }else{//2、 如果是普通用户则根据角色查询对应的菜单
          nodeList= sysMenuMapper.getMenuByUsername(username);
        }


        //2 使用hutool工具类把 List<SysMenu> 转为树形结构
          //2.1 配置 ---参考 https://hutool.cn/docs/#/core/%E8%AF%AD%E8%A8%80%E7%89%B9%E6%80%A7/%E6%A0%91%E7%BB%93%E6%9E%84/%E6%A0%91%E7%BB%93%E6%9E%84%E5%B7%A5%E5%85%B7-TreeUtil?id=%e4%bb%8b%e7%bb%8d
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
         //2.2 转换器
        List<Tree<String>> treeNodes = TreeUtil.build(nodeList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId()+"");
                    tree.setParentId(treeNode.getParentId()+"");
                    tree.setName(treeNode.getName());
                    // 扩展属性 ...
                    tree.putExtra("path", treeNode.getPath());
                    tree.putExtra("component",treeNode.getComponent());
                });

        return treeNodes;
    }
}




